from django.shortcuts import render
from django.views.generic import View
from  PMSP.utils.captcha.captcha import captcha
from django import http
from django_redis import get_redis_connection
import random
from PMSP.utils.yuntongxun.sms import CCP

# 1, 图片验证码
class ImageCodeView(View):
    def get(self,request,image_code_id):

        # 0，判断是否存在之前的图片验证码
        redis_conn = get_redis_connection("code")  # 获取redis连接对象
        prev_image_code_id = request.GET.get("prev_image_code_id")
        if prev_image_code_id:
            redis_conn.delete(f"image_code_id_{prev_image_code_id}")

        # 1,获取图片验证码
        _,text,image_data = captcha.generate_captcha()

        # 2，存储图片验证码到redis
        redis_conn.setex(f"image_code_id_{image_code_id}",300,text)

        # 测试直接返回图片验证码
        return http.HttpResponse(image_data,content_type="image/png")

# 2, 短信验证码
class SmsCodeView(View):
    def get(self,request,mobile):

        # 0,判断是否频繁发送了
        redis_conn = get_redis_connection("code")  # 获取redis连接对象
        send_flag = redis_conn.get(f"send_flag_{mobile}") # 获取标记
        if send_flag:
            return http.JsonResponse({"code":4001,"errmsg":"短信发送频繁,稍后试!"})

        # 1,获取参数
        image_code = request.GET.get("image_code") # 用户填写的值
        image_code_id = request.GET.get("image_code_id") # 图片验证码的编号

        # 2，参数校验
        # 2，1 为空检验
        if not all([image_code,image_code_id]):
            return http.JsonResponse({"code":4001,"errmsg":"参数不全"})

        # 2，2 根据image_code_id获取redis中的图片验证码
        redis_image_code =  redis_conn.get(f"image_code_id_{image_code_id}")

        # 2,3 判断redis中的图片验证码是否过期
        if not redis_image_code:
            return http.JsonResponse({"code":4001,"errmsg":"图片验证码已经过期"})

        # 2,4 判断是否正确
        if image_code != redis_image_code.decode():
            return http.JsonResponse({"code": 4001, "errmsg": "图片验证码填写错误"})

        # 2,5 删除redis中的图片验证码
        redis_conn.delete(f"image_code_id_{image_code_id}")

        # 3, 发送短信
        sms_code = "%06d"%random.randint(0,999999)

        # import time
        # time.sleep(5) # 模拟耗时任务

        # ccp = CCP()
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # 调度短信发送任务
        from PMSP.utils.celery_task.celery import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        # 3,1 判断短信验证码是否发送成功
        # if result == -1:
        #     return http.JsonResponse({"code": 4001, "errmsg": "短信验证码发送失败"})

        # 3,2 存储短信验证码到redis中
        pipeline = redis_conn.pipeline() # 获取管道（事务）对象
        pipeline.setex(f"sms_code_{mobile}",300,sms_code)
        pipeline.setex(f"send_flag_{mobile}",60,"True") # 设置一个标记
        pipeline.execute() # 提交事务

        # 4, 返回响应
        return http.JsonResponse({"code":0})